<template>
  <div>
    正在登录中,请稍后......
  </div>
</template>

<script setup>

import {onMounted} from "vue";
import {CommonServices} from "@/api/common";
import {getStore, setStore} from "@/api/utils";
import {getCurrentInstance} from "vue";
import router from "@/router";

let {proxy} = getCurrentInstance();
var openid = ''

onMounted(() => {
  loginByQQ();
})

/**
 * qq登录方法
 * @returns {Promise<void>}
 */
const loginByQQ = async () => {
  await getOpenIdByAccessToken();
  console.log(openid)
  const {data} = await CommonServices.loginByQQ({
    qq_open_id: openid,
    qq_app_id: getStore('qq_app_id')
  });
  if (data.code === 200) {
    proxy.$Message.success({
      content: '登录成功',
      duration: 1.5,
      closable: true,
      onClose: async () => {
        console.log(data)
        setStore('token', data.data.token);
        setStore('user_name', data.data.username)
        await CommonServices.GetAccountAuths();
        proxy.$router.push('/dashboard')
      }
    });
  } else {
    proxy.$Message.warning({
      content: data.data,
      duration: 1.5,
      closable: true,
      onClose: () => {
        router.replace('/login');
      }
    })
  }
  console.log(data);
}

/**
 * 通过access_token获取openid
 * @returns {Promise<void>}
 */
const getOpenIdByAccessToken = async () => {
  const {data} = await CommonServices.getOpenIdByAccessToken({
    access_token: getQuery('access_token')
  })
  if (data.code === 200) {
    console.log(data.data)
    openid = data.data.openid;
  } else {
    proxy.$Message.warning({
      content: data.data,
      duration: 1.5,
      closeable: true,
      onClose: () => {
        router.replace('/login')
      }
    })
  }
}

// 获取hash类型地址参数--qq
const getQuery = (val) => {
  const hash = location.hash.lastIndexOf('#');
  const query = location.hash.substring(hash + 1);

  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    if (pair[0] == val) {
      return pair[1];
    }
  }
  return (false);
}

</script>

<style scoped>

</style>
